package com.xl6667.controller;

import com.xl6667.domain.ResponseResult;
import com.xl6667.domain.dto.AdminUserInfoDto;
import com.xl6667.domain.dto.RoutersDto;
import com.xl6667.domain.dto.UserInfoDto;
import com.xl6667.domain.entity.LoginUser;
import com.xl6667.domain.entity.Menu;
import com.xl6667.domain.entity.User;
import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.exception.SystemException;
import com.xl6667.service.AdminUserService;
import com.xl6667.service.MenuService;
import com.xl6667.service.RoleService;
import com.xl6667.util.BeanCopyUtil;
import com.xl6667.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
public class loginController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        if (!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }

        return adminUserService.login(user);

    }

    @GetMapping("/getInfo")
    public ResponseResult getInfo(){
        //获取当前登录的用户
        LoginUser loginUser = SecurityUtil.getLoginUser();
        //根据用户id查询权限信息
        List<String> perms = menuService.selectPermsByUserId(loginUser.getUser().getId());
        //根据用户id查询角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(loginUser.getUser().getId());

        //获取用户信息
        User user = loginUser.getUser();
        UserInfoDto userInfoDto = BeanCopyUtil.copyBean(user, UserInfoDto.class);
        //封装数据返回

        AdminUserInfoDto adminUserInfoVo = new AdminUserInfoDto(perms,roleKeyList,userInfoDto);
        return ResponseResult.okResult(adminUserInfoVo);
    }
    @GetMapping("getRouters")
    public ResponseResult<RoutersDto> getRouters(){
        Long userId = SecurityUtil.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RoutersDto(menus));
    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return adminUserService.logout();
    }
}
